package com.ddx.service.impl;

import com.ddx.check.CheckOrderParamValidate;
import com.ddx.common.enums.ErrorCode;
import com.ddx.common.enums.OrderStatus;
import com.ddx.common.enums.ResultType;
import com.ddx.common.exception.BusinessException;
import com.ddx.common.exception.ResultModel;
import com.ddx.dao.*;
import com.ddx.dto.*;
import com.ddx.pojo.*;
import com.ddx.service.ICreateSerialNumService;
import com.ddx.service.IShoppingOrderService;
import com.ddx.service.IShoppingProductService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author dudianbo
 * @ClassName: ${CLASSNAME}
 * @Description: ${DESCRIPTION}
 * @date 2018/9/5
 */
@Service
public class ShoppingOrderServiceImpl implements IShoppingOrderService {

    private static Logger logger = LoggerFactory.getLogger(ShoppingOrderServiceImpl.class);

    @Autowired
    ICreateSerialNumService iCreateSerialNumService;
    @Autowired
    ShoppingProductMapper shoppingProductMapper;
    @Autowired
    ShoppingOrderMapper shoppingOrderMapper;
    @Autowired
    ShoppingOrderDetailMapper shoppingOrderDetailMapper;
    @Autowired
    ShoppingUserAddressMapper shoppingUserAddressMapper;
    @Autowired
    ShoppingStoreMapper shoppingStoreMapper;
    @Autowired
    ShoppingCartMapper shoppingCartMapper;
    @Autowired
    ShoppingPayFlowMapper shoppingPayFlowMapper;

    @Autowired
    ShoppingAccountMapper shoppingAccountMapper;
    @Autowired
    ShoppingSpecMapper shoppingSpecMapper;
    @Autowired
    IShoppingProductService iShoppingProductService;

    @Value("${fastdfs.server}")
    String imageAddress;

    /**
     * 创建订单
     *
     * @param shoppingOrderVo
     */
    @Override
    @Transactional
    public ShoppingPayVo createOrder(ShoppingOrderVo shoppingOrderVo) {
        CheckOrderParamValidate.checkCreateOrder(shoppingOrderVo);
        ShoppingPayVo shoppingPayVo=new ShoppingPayVo();
        ShoppingOrderDetailVo shoppingOrderDetailVo=shoppingOrderVo.getDetailVos().get(0);
        ShoppingProduct product = shoppingProductMapper.selectByPrimaryKey(Integer.parseInt(shoppingOrderDetailVo.getProductId()));
        String orderId = iCreateSerialNumService.createSerialNum(shoppingOrderVo.getUserId(), product.getId().toString());
        ShoppingOrder shoppingOrder = new ShoppingOrder();
        shoppingOrder.setOrderId(orderId);
        shoppingOrder.setOtherRequire(shoppingOrderVo.getOtherRequire());
        shoppingOrder.setStatus(OrderStatus.DAIFUKUAN.getValue());
        shoppingOrder.setCount(shoppingOrderVo.getDetailVos() == null ? 0 : shoppingOrderVo.getDetailVos().size());
        shoppingOrder.setShopId(product.getShopId());
        shoppingOrder.setUserId(shoppingOrderVo.getUserId());
        shoppingOrder.setAddressId(shoppingOrderVo.getAddressId());
        List<ShoppingOrderDetail> list = new ArrayList<>();
        BigDecimal amount = BigDecimal.ZERO;
        for (ShoppingOrderDetailVo detailVo : shoppingOrderVo.getDetailVos()) {
            ShoppingSpec shoppingSpec=shoppingSpecMapper.selectByPrimaryKey(Integer.parseInt(detailVo.getSpecId()));
            ShoppingOrderDetail shoppingOrderDetail = new ShoppingOrderDetail();
            ShoppingProduct shoppingProduct = shoppingProductMapper.selectByPrimaryKey(Integer.parseInt(detailVo.getProductId()));
            shoppingOrderDetail.setOrderId(orderId);
            shoppingOrderDetail.setNumber(detailVo.getNumber());
            shoppingOrderDetail.setProductId(detailVo.getProductId());
            shoppingOrderDetail.setPrice(shoppingSpec.getSpecPrice());
            amount = amount.add(shoppingSpec.getSpecPrice());
            shoppingOrderDetail.setProductName(shoppingProduct.getName());
            shoppingOrderDetail.setSpecId(detailVo.getSpecId());
            list.add(shoppingOrderDetail);
            shoppingOrderDetailMapper.insertSelective(shoppingOrderDetail);
            if(detailVo.getCartId()!=null){
                //删除购物车记录
                shoppingCartMapper.deleteByPrimaryKey(Integer.parseInt(detailVo.getCartId()));
            }
        }
        shoppingOrder.setAmount(amount);
        shoppingOrder.setPtotal(amount);
        shoppingOrderMapper.insertSelective(shoppingOrder);
        shoppingPayVo.setOrderId(orderId);
        ShoppingAccount shoppingAccount=shoppingAccountMapper.selectAccountByUserId(shoppingOrderVo.getUserId());
        shoppingPayVo.setBalance(shoppingAccount.getTotalAmount().subtract(shoppingAccount.getFrozenAmount()));
        return shoppingPayVo;
    }
    /**
     * 确认生成订单页面
     * @param shoppingCarts
     */
    @Override
    public ShoppingSettleVo createSettlePage(List<ShoppingCart> shoppingCarts, String userId) {
        ShoppingSettleVo shoppingSettleVo = new ShoppingSettleVo();
        List<ShoppingUserAddress> list = shoppingUserAddressMapper.selectAdressByUserId(userId);
        if (list != null && list.size() > 0) {
            shoppingSettleVo.setShoppingUserAddress(list.get(0));
        }
        ShoppingCartVo voList = new ShoppingCartVo();
        BigDecimal sumAmount=BigDecimal.ZERO;
        Integer count=0;
        for (ShoppingCart shoppingCart : shoppingCarts) {
            //用户从购物车进入结算页面
            if (shoppingCart.getId() != null) {
                ShoppingCart record=shoppingCartMapper.selectByPrimaryKey(shoppingCart.getId());
                ShoppingStore shoppingStore = shoppingStoreMapper.selectByPrimaryKey(Integer.parseInt(record.getStoreId()));
                voList.setStoreName(shoppingStore.getName());
                voList.setStoreId(shoppingStore.getId().toString());
                ShoppingCart cart = new ShoppingCart();
                cart.setStoreId(record.getStoreId());
                cart.setUserId(userId);
                //获取属于该商铺的所有商品
                List<ShoppingCart> products = shoppingCartMapper.selectByRecord(cart);
                List<ShoppingCartVo> vos = new ArrayList<>();
                for (ShoppingCart model : products) {
                    ShoppingSpec shoppingSpec=shoppingSpecMapper.selectByPrimaryKey(Integer.parseInt(model.getSpecId()));
                    if(model.getProductNumber()>Integer.parseInt(shoppingSpec.getSpecStock())){
                        throw new BusinessException(ErrorCode.BUSSINESS_ERROR_211);
                    }
                    ShoppingProduct shoppingProduct = shoppingProductMapper.selectByPrimaryKey(Integer.parseInt(model.getProductId()));
                    ShoppingCartVo shoppingCartVo = new ShoppingCartVo();
                    shoppingCartVo.setProductName(shoppingProduct.getName());
                    shoppingCartVo.setNowPrice(shoppingProduct.getNowPrice());
                    shoppingCartVo.setMemberPrice(shoppingSpec.getSpecPrice());
                    shoppingCartVo.setProductNumber(model.getProductNumber());
                    shoppingCartVo.setGold(shoppingSpec.getSpecPrice().multiply(shoppingProduct.getFeeRate()).setScale(2,BigDecimal.ROUND_DOWN));
                    shoppingCartVo.setSpecId(model.getSpecId());
                    shoppingCartVo.setSpecJson(shoppingSpec.getSpecJson());
                    shoppingCartVo.setId(model.getId());
                    shoppingCartVo.setPicture(imageAddress+shoppingProduct.getPicture());
                    shoppingCartVo.setProductId(shoppingProduct.getId().toString());
                    vos.add(shoppingCartVo);
                    //总件数
                    count=count+model.getProductNumber();
                    //总金额
                    BigDecimal amount=shoppingSpec.getSpecPrice().multiply(new BigDecimal(shoppingCart.getProductNumber().toString()));
                    sumAmount=sumAmount.add(amount);
                }
                voList.setVoList(vos);
                //用户从商品页直接购买
            } else if (shoppingCart.getProductId() != null&&shoppingCart.getSpecId()!=null) {
                List<ShoppingCartVo> vos = new ArrayList<>();
                ShoppingSpec shoppingSpec=shoppingSpecMapper.selectByPrimaryKey(Integer.parseInt(shoppingCart.getSpecId()));
                if(shoppingCart.getProductNumber()>Integer.parseInt(shoppingSpec.getSpecStock())){
                     throw new BusinessException(ErrorCode.BUSSINESS_ERROR_211);
                }
                ShoppingProduct shoppingProduct = shoppingProductMapper.selectByPrimaryKey(Integer.parseInt(shoppingCart.getProductId()));
                ShoppingCartVo shoppingCartVo = new ShoppingCartVo();
                shoppingCartVo.setProductName(shoppingProduct.getName());
                shoppingCartVo.setProductId(shoppingProduct.getId().toString());
                shoppingCartVo.setNowPrice(shoppingProduct.getNowPrice());
                shoppingCartVo.setMemberPrice(shoppingSpec.getSpecPrice());
                shoppingCartVo.setProductNumber(shoppingCart.getProductNumber());
                shoppingCartVo.setGold(shoppingSpec.getSpecPrice().multiply(shoppingProduct.getFeeRate()).setScale(2,BigDecimal.ROUND_DOWN));
                shoppingCartVo.setSpecId(shoppingCart.getSpecId());
                shoppingCartVo.setSpecJson(shoppingSpec.getSpecJson());
                shoppingCartVo.setPicture(imageAddress+shoppingProduct.getPicture());
                vos.add(shoppingCartVo);
                voList.setVoList(vos);
                ShoppingStore shoppingStore = shoppingStoreMapper.selectByPrimaryKey(Integer.parseInt(shoppingProduct.getShopId()));
                voList.setStoreName(shoppingStore.getName());
                voList.setStoreId(shoppingStore.getId().toString());
                count=count+shoppingCart.getProductNumber();
                BigDecimal amount=shoppingSpec.getSpecPrice().multiply(new BigDecimal(shoppingCart.getProductNumber().toString()));
                sumAmount=sumAmount.add(amount);
            }
        }
        shoppingSettleVo.setShoppingCartVos(voList);
        shoppingSettleVo.setSumCount(count);
        shoppingSettleVo.setSumAmount(sumAmount);
        return shoppingSettleVo;
    }

    @Override
    public ShoppingOrderVo orderInfo(String orderId) {
        ShoppingOrderVo shoppingOrderVo=new ShoppingOrderVo();
        ShoppingOrder shoppingOrder=shoppingOrderMapper.selectOrderByOrderId(orderId);
        BeanUtils.copyProperties(shoppingOrder,shoppingOrderVo);
        ShoppingUserAddress shoppingUserAddress=shoppingUserAddressMapper.selectByPrimaryKey(new Long(shoppingOrder.getAddressId()));
        shoppingOrderVo.setShoppingUserAddress(shoppingUserAddress);
        // 获取商品名字，图片，价格，会员价格，当前价格，进价
        List<ShoppingOrderDetail> shoppingOrderDetailList = shoppingOrderDetailMapper.selectOrderDetailByOrderId(shoppingOrder.getOrderId());
        if(shoppingOrderDetailList!=null&&shoppingOrderDetailList.size()>0){
            List<ShoppingOrderDetailVo> detailVos = new ArrayList<ShoppingOrderDetailVo>();
            shoppingOrderDetailList.stream().forEach(shoppingOrderDetail -> {
                ShoppingOrderDetailVo shoppingOrderDetailVo = new ShoppingOrderDetailVo();
                BeanUtils.copyProperties(shoppingOrderDetail,shoppingOrderDetailVo);
                ShoppingProduct shoppingProduct=shoppingProductMapper.selectByPrimaryKey(Integer.parseInt(shoppingOrderDetail.getProductId()));
                if(shoppingProduct!=null){
                    shoppingOrderDetailVo.setPicture(imageAddress + shoppingProduct.getPicture());
                    shoppingOrderDetailVo.setMember_price(shoppingProduct.getMemberPrice());
                    shoppingOrderDetailVo.setNow_price(shoppingProduct.getNowPrice());
                    detailVos.add(shoppingOrderDetailVo);
                }
            });
            shoppingOrderVo.setDetailVos(detailVos);
        }
        return shoppingOrderVo;
    }

    /**
     * 支付成功
     * @param shoppingPayFlow
     */
    @Override
    @Transactional
    public void paySuccess(ShoppingPayFlowWithBLOBs shoppingPayFlow) {
        logger.info("支付成功接口入参shoppingPayFlow={}",shoppingPayFlow);
        if(shoppingPayFlow.getDealStatus()==null||!ResultType.SUCCESS.getCode().equals(shoppingPayFlow.getDealStatus())){
            logger.info("支付非成功dealStatus={}",shoppingPayFlow.getDealStatus());
            return;
        }
        //校验订单
        ShoppingOrder shoppingOrder=shoppingOrderMapper.selectOrderByOrderId(shoppingPayFlow.getOrderId());
        if(shoppingOrder==null|| shoppingOrder.getAmount().compareTo(shoppingPayFlow.getAmount())!=0){
              throw new BusinessException(ErrorCode.ACCOUNT_ERROR_311);
        }
        //修改订单
        ShoppingPayFlow flow=new ShoppingPayFlow();
        flow.setOrderId(shoppingPayFlow.getOrderId());
        List<ShoppingPayFlowWithBLOBs> list=shoppingPayFlowMapper.selectByRecord(flow);
        //如果该笔订单没有插入过，则插入
        if(list==null||list.size()==0){
            ShoppingPayFlowWithBLOBs shoppingPayFlowWithBLOBs=new ShoppingPayFlowWithBLOBs();
            BeanUtils.copyProperties(shoppingPayFlow,shoppingPayFlowWithBLOBs);
            shoppingPayFlowMapper.insertSelective(shoppingPayFlowWithBLOBs);
        }else {
            ShoppingPayFlowWithBLOBs bloBs=list.get(0);
            if(ResultType.SUCCESS.getCode().equals(bloBs.getDealStatus())){
                logger.info("该支付接口已支付成功orderId={}",shoppingPayFlow.getDealStatus());
                return;
            }
            //根据第三方流水号查询该笔订单是否存在
            ShoppingPayFlowWithBLOBs shoppingPayFlowWithBLOBs = shoppingPayFlowMapper.selectByThirdPartyNo(shoppingPayFlow.getThirdPartyNo());
            if (shoppingPayFlowWithBLOBs == null) {
                shoppingPayFlowMapper.updateByOrderId(shoppingPayFlow);
            } else {
                if (ResultType.SUCCESS.getCode().equals(shoppingPayFlowWithBLOBs.getDealStatus())) {
                    return;
                }
                shoppingPayFlowMapper.updateByThirdPartyNo(shoppingPayFlow);
            }
        }
        //修改订单状态为待收货
        ShoppingOrder record=new ShoppingOrder();
        record.setOrderId(shoppingPayFlow.getOrderId());
        record.setStatus(OrderStatus.DAIFAHUO.getValue());
        shoppingOrderMapper.updateByOrderId(record);
    }
    /**
     * 订单取消
     * @param orderId
     */
    @Override
    public void orderCancal(String orderId) {
        logger.info("订单取消orderId={}",orderId);
        ShoppingOrder shoppingOrder=shoppingOrderMapper.selectOrderByOrderId(orderId);
        if(OrderStatus.DAIFUKUAN.getValue()!=shoppingOrder.getStatus()){
            throw new BusinessException(ErrorCode.ACCOUNT_ERROR_311);
        }
        ShoppingOrder record=new ShoppingOrder();
        record.setOrderId(orderId);
        record.setStatus(OrderStatus.QUXIAO.getValue());
        shoppingOrderMapper.updateByOrderId(record);

    }
    /**
     * 确认收货
     * @param orderId
     */
    @Override
    public void orderConfirm(String orderId) {
        logger.info("确认收货orderId={}",orderId);
        ShoppingOrder shoppingOrder=shoppingOrderMapper.selectOrderByOrderId(orderId);
        if(OrderStatus.DAISHOUHUO.getValue()!=shoppingOrder.getStatus()){
            throw new BusinessException(ErrorCode.ACCOUNT_ERROR_311);
        }
        ShoppingOrder record=new ShoppingOrder();
        record.setOrderId(orderId);
        record.setStatus(OrderStatus.DAIPINGJIA.getValue());
        shoppingOrderMapper.updateByOrderId(record);
    }

    /**
     * 我的订单list页面，0 待付款 1待发货 2待收货 3 待评价 4售后 5已售罄 6订单取消
     * @param userId
     * @param status
     * @return
     */
    @Override
    public List<ShoppingOrderVo> list(int userId, String status) {
        // 返回对象
        List<ShoppingOrderVo> list = new ArrayList<ShoppingOrderVo>();

        ShoppingOrderVo shoppingOrderVo=new ShoppingOrderVo();
        shoppingOrderVo.setUserId(String.valueOf(userId));
        // all 或者null ----代表是全部列表
        if(StringUtils.isBlank(status) || "-1".equals(status)){
        }else {
            shoppingOrderVo.setStatus(Integer.parseInt(status));
        }
        List<ShoppingOrder> shoppingOrderList=shoppingOrderMapper.selectOrderByUserId(shoppingOrderVo);
        if(shoppingOrderList !=null && shoppingOrderList.size() > 0){
            shoppingOrderList.stream().forEach(shoppingOrder -> {
                ShoppingOrderVo shoppingOrderVoTemp=new ShoppingOrderVo();
                BeanUtils.copyProperties(shoppingOrder,shoppingOrderVoTemp);
                // 获取店铺名字
                ShoppingStore shoppingStore = shoppingStoreMapper.selectByPrimaryKey(Integer.parseInt(shoppingOrder.getShopId()));
                if(shoppingStore!=null){
                    shoppingOrderVoTemp.setStoreName(shoppingStore.getName());
                }
                // 获取商品名字，图片，价格，会员价格，当前价格，进价
                List<ShoppingOrderDetail> shoppingOrderDetailList = shoppingOrderDetailMapper.selectOrderDetailByOrderId(shoppingOrder.getOrderId());
                if(shoppingOrderDetailList!=null&&shoppingOrderDetailList.size()>0){
                    List<ShoppingOrderDetailVo> detailVos = new ArrayList<ShoppingOrderDetailVo>();
                    shoppingOrderDetailList.stream().forEach(shoppingOrderDetail -> {
                        ShoppingOrderDetailVo shoppingOrderDetailVo = new ShoppingOrderDetailVo();
                        BeanUtils.copyProperties(shoppingOrderDetail,shoppingOrderDetailVo);
                        ShoppingProduct shoppingProduct=shoppingProductMapper.selectByPrimaryKey(Integer.parseInt(shoppingOrderDetail.getProductId()));
                        if(shoppingProduct!=null){
                            shoppingOrderDetailVo.setPicture(imageAddress + shoppingProduct.getPicture());
                            shoppingOrderDetailVo.setMember_price(shoppingProduct.getMemberPrice());
                            shoppingOrderDetailVo.setNow_price(shoppingProduct.getNowPrice());
                            detailVos.add(shoppingOrderDetailVo);
                        }
                    });
                    shoppingOrderVoTemp.setDetailVos(detailVos);
                }
                list.add(shoppingOrderVoTemp);
            });
        }

        return list;
    }

    /**
     * 查看物流状态,0 待付款 1待发货 2待收货 3 待评价 4售后 5已售罄 6订单取消
     *
     * @param orderId
     * @return
     */
    @Override
    public Map<String, String> orderStatus(String orderId) throws Exception{
        Map<String, String> map = new HashMap<String, String>();
        ShoppingOrder shoppingOrder = shoppingOrderMapper.selectOrderByOrderId(orderId);
        if(shoppingOrder == null){
            throw new BusinessException(ErrorCode.BUSSINESS_ERROR_201,"订单不存在");
        }
        map.put("orderId",shoppingOrder.getOrderId());
        map.put("status",shoppingOrder.getStatus().toString());
        map.put("expressCompanyName",shoppingOrder.getExpressCompanyName());
        return map;
    }

    @Override
    public void editWuLiu(ShoppingOrderVo shoppingOrderVo) throws Exception {
        shoppingOrderMapper.updateByOrderId(shoppingOrderVo);
    }

    @Override
    public Map<Integer, BigDecimal> getProductSaleAmount(List<Integer> productIdList) {
        Map<Integer, BigDecimal> returnMap = new HashMap<>();
        List<OrderProductSaleInfo> orderProductSaleInfos = shoppingOrderMapper.selectProductSaleAmount(productIdList);
        for (OrderProductSaleInfo orderProductSaleInfo : orderProductSaleInfos) {
            returnMap.put(orderProductSaleInfo.getProductId(), orderProductSaleInfo.getSaleAmount());
        }
        return returnMap;
    }

    @Override
    public ResultModel getOrderLiftForSupplier(int userId, SupplierOrderDto supplierOrderDto) {
        Map<String, Object> returnMap = new HashMap<>();
        ShoppingStore shoppingStore = shoppingStoreMapper.selectByUserId(userId);
        int count = shoppingOrderMapper.countWithSupplier(shoppingStore.getId(), supplierOrderDto.getStatus());
        List<FullOrder> shoppingOrderList = shoppingOrderMapper.selectListWithSupplier(shoppingStore.getId(), supplierOrderDto.getStatus(), supplierOrderDto.getIndex() * supplierOrderDto.getSize(), supplierOrderDto.getSize());
        for(FullOrder fullOrder:shoppingOrderList){
            fullOrder.setPicture(imageAddress + fullOrder.getPicture());
        }
        returnMap.put("count", count);
        returnMap.put("orderList", shoppingOrderList);
        ResultModel resultModel = ResultModel.getSuccessInstance();
        resultModel.setData(returnMap);
        return resultModel;
    }

    @Override
    public ResultModel send(String orderId, String companyName, String expressNo) {
        shoppingOrderMapper.send(orderId, companyName, expressNo);
        return ResultModel.getSuccessInstance();
    }

    @Override
    public ResultModel submitOrder(String userId, String productId, Integer productNumber, String userAddressId) {
        ResultModel resultModel = new ResultModel();
        ShoppingProduct product = shoppingProductMapper.selectByPrimaryKey(Integer.parseInt(productId));
        ShoppingUserAddress shoppingUserAddress = shoppingUserAddressMapper.selectByPrimaryKey(Long.parseLong(userAddressId));

        BigDecimal orderPrice;
        orderPrice = product.getNowPrice().add(product.getFreightPrice()).multiply(new BigDecimal(productNumber));
        ShoppingOrder order = new ShoppingOrder();
        order.setOrderId(String.valueOf(System.currentTimeMillis()));
        order.setStatus(OrderStatus.DAIFUKUAN.getValue());
        order.setAmount(orderPrice);
        order.setCount(productNumber);
        order.setPtotal(orderPrice);
        order.setUserId(userId);
        order.setShopId(product.getShopId());
        order.setAddressId(userAddressId);
        order.setProvince(shoppingUserAddress.getProvince());
        order.setCity(shoppingUserAddress.getCity());
        order.setArea(shoppingUserAddress.getArea());
        order.setDetail(shoppingUserAddress.getAddress());
        shoppingOrderMapper.insertSelective(order);

        ShoppingOrderDetail orderDetail = new ShoppingOrderDetail();
        orderDetail.setOrderId(order.getOrderId());
        orderDetail.setNumber(productNumber);
        orderDetail.setPrice(product.getPrice());
        orderDetail.setProductName(product.getTitle());
        orderDetail.setProductId(productId);
        orderDetail.setNowPrice(product.getNowPrice());
        shoppingOrderDetailMapper.insertSelective(orderDetail);

        product.setSellcount(product.getSellcount() + 1);
        shoppingProductMapper.updateByPrimaryKey(product);

        Map<String, Object> returnMap = new HashMap<>();
        returnMap.put("orderPrice", orderPrice);
        returnMap.put("orderId", order.getOrderId());
        resultModel.setData(returnMap);
        return resultModel;
    }
}
